import { defineStore } from 'pinia'

export const chatStore = defineStore('chat', () => {
    const nowChatId = ref<string>('1')
    const chatList = ref<Chat[]>([{
        id: '1',
        title: '新的对话',
        messages: [],
    }])
    const getNowChat = computed(() => {
        return chatList.value.find(item => item.id === nowChatId.value)
    })
    const createChat = () => {
        const id = `id-${uuidV4()}`
        return {
            id,
            title: '新的对话',
            messages: [],
            create: new Date(),
            update: new Date(),
        }
    }
    const setNowChatId = (id: string) => {
        nowChatId.value = id
    }
    const addChat = () => {
        if (getNowChat.value?.messages.length === 0) {
            return
        }
        const chat = createChat()
        chatList.value.push(chat)
        setNowChatId(chat.id)
        return chat
    }
    const addMessage = () => {
        const chat = getNowChat.value
        const id = `id-${uuidV4()}`
        if (chat) {
            chat.messages.push({
                id,
                content: '',
                create: new Date(),
                update: new Date(),
                readonly: true
            })
        }
        return id
    }
    const updateMessage = (chatId: string, messageId: string, content: string) => {
        const chat = chatList.value.find(item => item.id === chatId)
        if (chat) {
            const message = chat.messages.find(item => item.id === messageId)
            if (message) {
                message.content = content
                message.update = new Date()
            }
        }
    }
    const getMessage = (chatId: string, messageId: string) => {
        const chat = chatList.value.find(item => item.id === chatId)
        if (chat) {
            return chat.messages.find(item => item.id === messageId)
        }
        return null
    }
    return {
        addMessage,
        getNowChat,
        setNowChatId,
        addChat,
        updateMessage,
        getMessage
    }
})